package com.bjpowernode.web.controller;

import com.bjpowernode.commons.model.User;
import com.bjpowernode.commons.service.UserService;
import com.bjpowernode.commons.utils.DirUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("img")
@CrossOrigin
public class ImageController {
    @Value("${savePath}")
    private String savePath;

    @Value("${imgServer}")
    private String imgServer;

    @Resource
    private RedisTemplate redisTemplate;

    @DubboReference
    private UserService userService;

    @PostMapping("uploadHeaderImg")
    // MultipartFile类型专门用来接收文件类型，变量的名字必须和提交的参数名一致
    public String uploadHeaderImg(MultipartFile headerImg,
                                  @RequestHeader(value = "token", required = false) String token) throws IOException {
        // 文件名称，可能会出现重名的情况，因此不使用
        //String filename = headerImg.getOriginalFilename();
        // 使用UUID随机命名，但是会导致一个用户在多次更换头像时，之前的头像没有删除，占用硬盘，所以UUID不合适
        //String filename = UUID.randomUUID().toString();
        // 用户id是唯一的
        User user = (User) redisTemplate.opsForValue().get(token);
        String filename = user.getId().toString();

        /*
            采用目录分离技术将图片打散存储
            目标：在“savePath”下生成10级目录，每个目录下最多100个文件夹
            "/0~99/0~99/0~99/0~99/0~99/0~99/0~99/0~99/0~99/0~99/"
         */
        String dirs = DirUtils.randomDirs(2, 10);
        File targetDir = new File(savePath + dirs);

        targetDir.mkdirs(); // 如果不存在，则创建

        headerImg.transferTo(new File(targetDir, filename));
        // http://127.0.0.1/img/2/8/30
        String headerImage = imgServer + "img/" + dirs + filename;
        userService.updateHeaderImage(user.getId(), headerImage);

        return headerImage;
    }
    // “/img/**”: 匹配以“/img/”开头的所有请求
    @GetMapping("**")
    public void showImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // http://127.0.0.1/xxx  uri: /xxx
        String uri = request.getRequestURI();
        // /img//9/3/30
        System.out.println("uri="+uri);
        uri = uri.substring(4);

        // 输入流读取文件
        InputStream in = new FileInputStream(savePath + uri);

        // 客户端输出流写文件
        OutputStream out = response.getOutputStream();

        byte[] bytes = new byte[1024];
        int len;
        while ((len = in.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }

        out.close();
        in.close();
    }
}
